package com.ionehe.group.common.uaa.ex.application.rest;

import com.ionehe.group.common.io.Response;
import com.ionehe.group.common.uaa.ex.application.converter.FunctionVOConvert;
import com.ionehe.group.common.uaa.ex.application.model.FunctionVO;
import com.ionehe.group.common.uaa.ex.domain.service.UserReadService;
import com.ionehe.group.common.uaa.ex.dto.ForestNodeMerger;
import com.ionehe.group.common.uaa.ex.dto.FunctionDTO;
import com.ionehe.group.common.uaa.ex.dto.UserDetailDTO;
import com.ionehe.group.common.uaa.ex.dto.UserInfoDTO;
import com.ionehe.group.common.uaa.ex.enums.ErrorMessages;
import com.ionehe.group.common.uaa.ex.utils.LoginUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 秀
 **/
@RestController
@RequestMapping("/api/uaa/tree")
@Api(value = "uaa-权限树相关服务", tags = "uaa-公共服务")
public class UaaTreeController {
    @Resource
    private FunctionVOConvert functionVOConvert;
    @Autowired
    private LoginUtils loginUtil;
    @Autowired
    private UserReadService userReadService;

    @GetMapping("/function")
    @ApiOperation("获取当前登陆用户的权限树")
    public Response<List<FunctionVO>> getTree(){
        Response<UserDetailDTO> res = loginUtil.getCurrentUser();
        if (!res.success() || res.getData() == null) {
            return Response.no(ErrorMessages.USER_NOT_LOGIN.toString());
        }

        UserDetailDTO userDetail = res.getData();
        UserInfoDTO userInfoDTO = userDetail.getUserInfoDTO();

        Response<List<FunctionDTO>> resListRes = userReadService.getResourceList(userInfoDTO.getTerminal() + "_" + userInfoDTO.getPhone());
        if (!resListRes.success()) {
            return Response.no(resListRes.getMessage());
        }
        List<FunctionDTO> data = resListRes.getData();
        return Response.yes(functionVOConvert.dto2vo(ForestNodeMerger.merge(data)));
    }
}
